from gurobipy import *
import math
import random
import sys
import numpy as np
import copy
import xlsxwriter
import matplotlib.pyplot as plt
import datetime
import time
import pandas as pd
import xlrd
import openpyxl


class Node():
    def __init__(self):
        self.Num = 0
        self.Name = None
        self.Longitude = 0
        self.Latitude = 0
        self.Demand = 0
        self.Fixed_Cost = 0

class Model():
    def __init__(self):
        self.I = []
        self.J = []
        self.node_num = 0
        self.cost = {}
        self.distance = {}

        self.x = []
        self.y = []
        self.z = 0


def Node_information(node):
    print('-----')
    print('node_num:',node.Num)
    print('node_name:',node.Name)
    print('node.Longitude:',node.Longitude)
    print('node.Latitude:',node.Latitude)
    print('node.Demand:',node.Demand) # h
    print('node.Fixed_Cost:',node.Fixed_Cost)

def ReadData(filepath_1,filepath_2,model):
    df_1 = pd.read_excel(filepath_1)
    for i in range(0,df_1.shape[0]):
        node = Node()
        node.Num = i
        node.Name = df_1['Name'][i]
        node.Longitude = df_1['Longitude'][i]
        node.Latitude = df_1['Latitude'][i]
        node.Demand = df_1['Demand'][i]
        node.Fixed_Cost = df_1['Fixed_Cost'][i]
        model.I.append(node)
        model.J.append(node)
        model.node_num = model.node_num + 1

    # for node in model.I:
    #     Node_information(node)

    df_2 = pd.read_excel(filepath_2)
    for i in range(0,df_2.shape[0]):
        for j in range(i,df_2.shape[0]):
            model.cost[i,j] = df_2[i][j]
            model.distance[i,j] = model.cost[i,j]*2
            model.cost[j,i] = model.cost[i,j]
            model.distance[j,i] = model.distance[i,j]

def SCLP(x):

    x = {}
    a = {}
    for i in range(model.node_num):
        x[i] = m.addVars(0,1,vtype = GRB.BINARY)
        for j in range(model.node_num):
            a[i,j] = m.addVars(0,1,vtype = GRB.BINARY)
    
    obj = LinExpr(0)
    sum = 0
    for i in range(model.node_num):
        obj.addTerms(x[i],1)
    model.setObjective(obj,GRB.MINIMIZE)

    # 约束
    for i in range (model.node_num):
        lhs = LinExpr(0)
        for j in range(model.node_num):
            lhs.addTerms(x[j],a[i,j])
        model.addConstr(lhs >= 1)
    
    model.optimiaze()

    for key in x.key():
        print(key)

def pcp(r_L = 0,r_U = 2743.3,p = 6,eps = 0.1):
    while (1):
        r = (r_L + r_U) / 2
        x = SCLP()

        if sum(x) <= p:
            r_U = r
        else:
            r_L = r
        if (r_U - r_L < eps):
            break 
    return x,r_U
    

if __name__ == '__main__':
    filepath_1 = r'88node_Node.xlsx'
    filepath_2 = r'88node_Cost.xlsx'
    model = Model()
    ReadData(filepath_1,filepath_2,model)
    pcp(r_L = 0,r_U = 2743.3,p = 6,eps = 0.1)